<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../jquery.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 300px;
            height: 2000px;
            background-color: indianred;
            margin-top: 500px;
        }

        a {
            position: fixed;
            right: 0;
            top: 500px;
            display: none;
        }
    </style>
</head>

<body>
    <div></div>
    <a href="javascript:;">返回顶部</a>
    <script>
        $(function () {
            //div距离文档顶部的值
            var boxTop = $("div").offset().top;
            $(window).scroll(function () {
                if ($(document).scrollTop() >= boxTop) {
                    $("a").fadeIn();
                } else {
                    $("a").fadeOut();
                }
                $("a").on("click", function () {
                    // $(document).scrollTop(0);
                    $("body,html").stop().animate({
                        scrollTop: 0
                    })
                })
            })
        })
    </script>
</body>

</html>